package cdu.xjj.service.impl;

import cdu.xjj.mapper.EmpExprMapper;
import cdu.xjj.mapper.EmpMapper;
import cdu.xjj.pojo.*;
import cdu.xjj.service.EmpLogService;
import cdu.xjj.service.EmpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.autoconfigure.PageHelperProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private PageHelperProperties pageHelperProperties;
    @Autowired
    private EmpLogService empLogService;


    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {

        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());

        List<Emp> emplist = empMapper.list(empQueryParam);
        //3：封装 结果
        Page<Emp> P= (Page<Emp>) emplist;
        return new PageResult<Emp>(P.getTotal(),P.getResult());
    }

    @Transactional
    @Override
    public void save(Emp emp) {

        //无论成功还是失败都记录日志
        try {
            //先插入员工信息
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insert(emp);

            //保存员工工作经历
            List<EmpExpr> exprList=emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)){
                exprList.forEach(empExpr -> {
                    empExpr.setEmpId(emp.getId());
                });
                empExprMapper.insertBatch(exprList);
            }

        } finally {

            EmpLog empLog=new EmpLog(null,LocalDateTime.now(),"新增员工："+ emp);
            empLogService.insertLog(empLog);
        }


    }
}
